﻿using System;
using System.Web;
using System.Web.Mvc;
using Liber;
using Liber.WEB;


namespace SoBusiness.Controllers
{
    /// <summary>
    /// 企业应用入口
    /// </summary>
    [NoSession]
    public class SoBizController : LiberController
    {
        public SoBizController()
        {
        }

        public RedirectResult Index()
        {
            return Redirect("/Index.html");
        }

        public ActionResult LoginForm()
        {
            if (Session["uid"] != null)
            {
                return null;
            }
            return View();
        }

        public RedirectResult LoginEnd()
        {
            var uid = Session["uid"];
            if (uid != null)
            {
                //TODO:根据用户设置跳转不同的页面
                if (Session["from"] != null&&Session["from"].ToString()!="/Index.html")
                {
                    return Redirect(Session["from"].ToString());
                }
                else
                {
                    return Redirect("/MyBiz/Dashbord");
                }
            }
            else
            {
                return Redirect("/Index.html");
            }
            
        }

        public RedirectResult Loginout()
        {
            Session.RemoveAll();
            return Redirect("/Index.html");
        }

        [HttpPost]
        public JsonResult Login()
        {
            string key = Request.Params["key"];
            string pass = Request.Params["pass"];
            string opensrc = Request.Params["opensrc"];
            if (string.IsNullOrWhiteSpace(key)&&string.IsNullOrWhiteSpace(opensrc))
            {
                return Json(FnResult<DyObject>.Failure("SoBizController", "NoKey").SetError("acnt","no acnt").SetError("opensrc","no opensrc"));
            }
            else if (opensrc == "wechat" &&!string.IsNullOrWhiteSpace(TLB2BController.IsWxLogined(HttpContext)))
            {
                var r = API.GetOpenSession(TLB2BController.IsWxLogined(HttpContext), opensrc);
                if (!r.IsPositive)
                {
                    return Json(r);
                }
                else
                {
                    SetLoginStatus(ControllerContext.HttpContext, r.Data);
                    return Json(r);
                }
            }
            else
            {
                var r = API.GetSession(key, pass);
                if (!r.IsPositive)
                {
                    return Json(r);
                }
                else
                {
                    SetLoginStatus(ControllerContext.HttpContext, r.Data);
                    return Json(r);
                }
            }         
        }
    }
}
